package com.chunxuan.langquan.ui.activity.store;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.GsonUtils;
import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.Base2Activity;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Config;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.CarProductEntity;
import com.chunxuan.langquan.dao.bean.DeliveryEntity;
import com.chunxuan.langquan.dao.bean.FreightPrice;
import com.chunxuan.langquan.dao.bean.OrderEntity;
import com.chunxuan.langquan.dao.bean.ReceiptAddressInfo;
import com.chunxuan.langquan.dao.bean.WxPayEntity;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.support.util.GlideUtil;
import com.chunxuan.langquan.ui.activity.AddressManageActivity;
import com.chunxuan.langquan.ui.activity.store.adapter.BaseAdapter;
import com.chunxuan.langquan.ui.activity.store.adapter.BaseViewHolder;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.arad.util.UIUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.ObservableSource;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class OrdersActivity extends Base2Activity {

    private RecyclerView rlv;
    private ImageView ivBack;
    private TextView tvName;
    private TextView tvPhone;
    private TextView tvAddress;
    private TextView tvTotalPrice;
    private FrameLayout frameLayout;
    private TextView tvDetail;
    private List<CarProductEntity> listProduct;
    private TextView tvSubmitOrder;
    private CheckBox cbAli;
    private CheckBox cbWx;
    private CardView cardViewAddress;
    private LinearLayout llDelivery;
    private TextView tvFreight;
    private TextView tvDelivery;
    private EditText etBackup;
    ReceiptAddressInfo addressInfo;
    private DeliveryEntity currentDelivery;
    private  List<DeliveryEntity> listDelivery;
    private OptionsPickerView pvOptions;
    private double freightPrice = 0;
    private int disPrice=0;//新用户优惠价格
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Map<String, String> h = (Map<String, String>) msg.obj;
            if ("9000".equals(h.get("resultStatus"))) {
                ToastUtils.showShort("支付成功");
            } else {
                ToastUtils.showShort("支付未完成");
            }
        }
    };

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_order_detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rlv = findViewById(R.id.rlv);
        ivBack = findViewById(R.id.iv_back);
        tvName = findViewById(R.id.tv_order_customer_name);
        tvPhone = findViewById(R.id.tv_order_customer_phone);
        tvAddress = findViewById(R.id.tv_order_address_detail);
        tvTotalPrice = findViewById(R.id.tv_order_total_price);
        frameLayout = findViewById(R.id.fr);
        tvDetail = findViewById(R.id.tv_order_total_discount_info);
        tvSubmitOrder = findViewById(R.id.tv_order_detail_submit);
        cbAli = findViewById(R.id.cb_ali);
        cbWx = findViewById(R.id.cb_wx);
        cardViewAddress = findViewById(R.id.cv_order_detail_address);
        llDelivery = findViewById(R.id.ll_delivery);
        tvDelivery = findViewById(R.id.tv_delivery);
        tvFreight = findViewById(R.id.tv_freight);
        etBackup = findViewById(R.id.et_backup);
        initDeliveryDialog();
        cardViewAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(AddressManageActivity.class, 2);
            }
        });
        requestAddress();
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tvDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDetail();
            }
        });

        tvSubmitOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitOrder();
            }
        });
        cbAli.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cbWx.setChecked(false);
                } else {
                    cbWx.setChecked(true);
                }
            }
        });
        cbWx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cbAli.setChecked(false);
                } else {
                    cbAli.setChecked(true);
                }
            }
        });


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rlv.setLayoutManager(linearLayoutManager);
        rlv.getRecycledViewPool().setMaxRecycledViews(0, 0);
        Adapter adapter = new Adapter();
        String data = getIntent().getStringExtra("data");
        Type type = GsonUtils.getListType(CarProductEntity.class);
        listProduct = GsonUtils.fromJson(data, type);
        List<?> couponList=new ArrayList<>();
        if(null!=listProduct&&listProduct.size()>0){
            couponList=listProduct.get(0).getCoupon();
            if(null!=couponList&&couponList.size()>0){
                disPrice=5;
                tvDetail.setText("共节省"+disPrice+"元,明细");
            }else{
                disPrice=0;
                tvDetail.setText("明细");
            }
        }

        adapter.setDatas(listProduct);
        rlv.setAdapter(adapter);
        tvTotalPrice.setText("合计  ￥" + (getTotalPrice(listProduct) - disPrice+freightPrice));

    }

    @SuppressLint("CheckResult")
    public void requestAddress() {
        APIRetrofit.getDefault().getAddressList(Global.HEADER, "")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<BaseResult2<List<ReceiptAddressInfo>>>() {
                    @Override
                    public void accept(BaseResult2<List<ReceiptAddressInfo>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            if (null != listBaseResult2.getData() && listBaseResult2.getData().size() > 0) {
                                addressInfo = listBaseResult2.getData().get(0);
                                tvAddress.setText(addressInfo.getAddress());
                                tvName.setText(addressInfo.getName());
                                tvPhone.setText(addressInfo.getMobile());
                            }
                        } else {
                            ToastUtils.showShort(listBaseResult2.getMsg());
                        }
                    }
                })
                .observeOn(Schedulers.io())
                .flatMap(new Function<BaseResult2<List<ReceiptAddressInfo>>,
                        ObservableSource<BaseResult2<List<DeliveryEntity>>>>() {
                    @Override
                    public ObservableSource<BaseResult2<List<DeliveryEntity>>> apply(BaseResult2<List<ReceiptAddressInfo>> result1) throws Exception {

                        if (result1.isSuccess() && null != result1.getData() && result1.getData().size() > 0) {
                            return APIRetrofit.getDefault().getDelivery(Global.HEADER,
                                    result1.getData().get(0).getCity_id() + "");
                        }
                        return APIRetrofit.getDefault().getDelivery(Global.HEADER,
                                "0");
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<BaseResult2<List<DeliveryEntity>>>() {
                    @Override
                    public void accept(BaseResult2<List<DeliveryEntity>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            if (null != listBaseResult2.getData() && listBaseResult2.getData().size() > 0) {
                                currentDelivery = listBaseResult2.getData().get(0);
                                tvDelivery.setText(currentDelivery.getName());
                                listDelivery = listBaseResult2.getData();
                                llDelivery.setOnClickListener(v -> {
                                    pvOptions.setPicker(listBaseResult2.getData());
                                    pvOptions.show();
                                });
                            }
                        } else {
                            ToastUtils.showShort(listBaseResult2.getMsg());
                        }
                    }
                })
                .observeOn(Schedulers.io())
                .flatMap(new Function<BaseResult2<List<DeliveryEntity>>, ObservableSource<BaseResult2<FreightPrice>>>() {
                    @Override
                    public ObservableSource<BaseResult2<FreightPrice>> apply(@io.reactivex.annotations.NonNull BaseResult2<List<DeliveryEntity>> result2) throws Exception {
                        if (null != result2.getData() && result2.getData().size() > 0&&addressInfo!=null) {
                            return APIRetrofit.getDefault().getFreightPrice(Global.HEADER,addressInfo.getCity_id()+"",
                                    result2.getData().get(0).getId()+"",getTotalNum()+"");
                        }
                        return null;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResult2<FreightPrice>>() {
                    @Override
                    public void accept(BaseResult2<FreightPrice> result2) throws Exception {
                        if (result2.isSuccess()) {
                            freightPrice = result2.getData().getDelivery_price();
                            tvFreight.setText(String.format("￥%s", result2.getData().getDelivery_price()));
                            tvTotalPrice.setText("合计  ￥" + (getTotalPrice(listProduct) - disPrice+freightPrice));
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();

                    }
                });

    }

    @SuppressLint("CheckResult")
    public void requestDelivery(String city_id) {
        APIRetrofit.getDefault().getDelivery(Global.HEADER, city_id)
                .compose(RxUtil.<BaseResult2<List<DeliveryEntity>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<DeliveryEntity>>>() {
                    @Override
                    public void accept(BaseResult2<List<DeliveryEntity>> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            if (null != result2.getData() && result2.getData().size() > 0) {
                                currentDelivery = result2.getData().get(0);
                                tvDelivery.setText(currentDelivery.getName());
                                listDelivery = result2.getData();
                                llDelivery.setOnClickListener(v -> {
                                    pvOptions.setPicker(result2.getData());
                                    pvOptions.show();
                                });
                                requestFreight();
                            }
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取收货地址列表失败");
                    }
                });

    }

    @SuppressLint("CheckResult")
    public void requestFreight(){
        APIRetrofit.getDefault().getFreightPrice(Global.HEADER,addressInfo.getCity_id()+"",currentDelivery.getId()+"",getTotalNum()+"")
                .compose(RxUtil.<BaseResult2<FreightPrice>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<FreightPrice>>() {
                    @Override
                    public void accept(BaseResult2<FreightPrice> result2) throws Exception {
                        if (result2.isSuccess()) {
                            freightPrice = result2.getData().getDelivery_price();
                            tvFreight.setText(String.format("￥%s", result2.getData().getDelivery_price()));
                            tvTotalPrice.setText("合计  ￥" + (getTotalPrice(listProduct) - disPrice+freightPrice));
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    public void initDeliveryDialog(){
        //条件选择器
        pvOptions =
                new OptionsPickerBuilder(OrdersActivity.this,
                        new OnOptionsSelectListener() {
                            @Override
                            public void onOptionsSelect(int options1, int option2,
                                                        int options3, View v) {
                                if (listDelivery == null){
                                    return;
                                }
                                currentDelivery = listDelivery.get(options1);
                                tvDelivery.setText(currentDelivery.getName());
                                requestFreight();
                            }
                        }).build();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 200 && requestCode == 2) {

            ReceiptAddressInfo receiptAddressInfo = GsonUtils.fromJson(data.getStringExtra(
                    "address"), ReceiptAddressInfo.class);
            addressInfo = receiptAddressInfo;
            tvAddress.setText(addressInfo.getAddress());
            tvName.setText(addressInfo.getName());
            tvPhone.setText(addressInfo.getMobile());
            requestDelivery(addressInfo.getCity_id()+"");
        }
    }

    public int getTotalPrice(List<CarProductEntity> datas) {
        int totalPrice = 0;
        for (int i = 0; i < datas.size(); i++) {
            CarProductEntity productEntity = datas.get(i);
            totalPrice += (productEntity.getSales_price() * productEntity.getNumber());
        }
        return totalPrice;
    }

    public int getTotalNum(){
        int totalNum = 0;
        for (int i = 0; i < listProduct.size(); i++) {
            CarProductEntity productEntity = listProduct.get(i);
            totalNum += (productEntity.getNumber());
        }
        return  totalNum;
    }

    public void showDetail() {
        View view = View.inflate(this, R.layout.pop_store_detail, null);
        TextView tv_discount=view.findViewById(R.id.tv_discount);
        RelativeLayout rlDiscount=view.findViewById(R.id.rl_discount);
        TextView tvAllPrice = view.findViewById(R.id.tv_all_price_ll);
        TextView tvDetailFreight = view.findViewById(R.id.tv_detail_freight);
        tvAllPrice.setText("￥" + getTotalPrice(listProduct));
        tvDetailFreight.setText("￥"+freightPrice);
        TextView tvTotalPrice = view.findViewById(R.id.tv_total_price_actually);
        tvTotalPrice.setText("￥" + (getTotalPrice(listProduct) - disPrice+freightPrice));
        PopupWindow popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popWindow.setOutsideTouchable(true);
        popWindow.setAnimationStyle(R.style.popupwindow_anim_style);
        popWindow.showAtLocation(frameLayout, Gravity.BOTTOM, 0, UIUtils.convertDpToPixel(this,
                60));
        if(disPrice==0){
            tv_discount.setVisibility(View.GONE);
            rlDiscount.setVisibility(View.GONE);
        }else{
            tv_discount.setVisibility(View.VISIBLE);
            rlDiscount.setVisibility(View.VISIBLE);
        }
    }

    @SuppressLint("CheckResult")
    public void submitOrder() {
        StringBuilder product_id = new StringBuilder();
        StringBuilder product_num = new StringBuilder();
        for (int i = 0; i < listProduct.size(); i++) {
            product_id.append(listProduct.get(i).getProduct_id()).append(",");
            product_num.append(listProduct.get(i).getNumber()).append(",");
        }
        String prid = product_id.substring(0, product_id.length() - 1);
        String num = product_num.substring(0, product_num.length() - 1);
        if (addressInfo == null){
            ToastUtils.showShort("请填写收货地址");
            return;
        }
        APIRetrofit.getDefault().requestGoOrder(Global.HEADER, prid, num, null,
                addressInfo.getCity_id(), addressInfo.getId(),currentDelivery.getId(),etBackup.getText().toString())
                .compose(RxUtil.<BaseResult2<OrderEntity>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<OrderEntity>>() {
                    @Override
                    public void accept(BaseResult2<OrderEntity> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            final String orderInfo = result2.getData().getOrder_id();   // 订单信息
                            if (cbAli.isChecked()) {
                                requestAliPay(orderInfo);
                            } else {
                                requestWxPay(orderInfo);
                            }
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("下单失败");
                    }
                });
    }

    @SuppressLint("CheckResult")
    public void requestAliPay(String orderInfo) {
        APIRetrofit.getDefault().alipay(Global.HEADER, orderInfo)
                .compose(RxUtil.<BaseResult2<String>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<String>>() {
                    @Override
                    public void accept(BaseResult2<String> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            final String orderInfo = result2.getData();   // 订单信息

                            Runnable payRunnable = new Runnable() {
                                @Override
                                public void run() {
                                    PayTask alipay = new PayTask(OrdersActivity.this);
                                    Map<String, String> result = alipay.payV2(orderInfo, true);
                                    Message msg = new Message();
                                    msg.what = 1;
                                    msg.obj = result;
                                    mHandler.sendMessage(msg);
                                }
                            };
                            // 必须异步调用
                            Thread payThread = new Thread(payRunnable);
                            payThread.start();
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取支付信息失败");
                    }
                });
    }

    @SuppressLint("CheckResult")
    public void requestWxPay(String orderInfo) {
        APIRetrofit.getDefault().wxpay(Global.HEADER, orderInfo)
                .compose(RxUtil.<BaseResult2<WxPayEntity>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<WxPayEntity>>() {
                    @Override
                    public void accept(BaseResult2<WxPayEntity> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            final WxPayEntity orderInfo = result2.getData();   // 订单信息
                            IWXAPI api = WXAPIFactory.createWXAPI(OrdersActivity.this,
                                    Config.WX_APP_ID);
                            api.registerApp(Config.WX_APP_ID);
                            PayReq request = new PayReq();
                            //
                            request.appId = orderInfo.getAppid();
                            request.partnerId = orderInfo.getOrderInfo().getPartnerid();
                            request.prepayId = orderInfo.getPrepay_id();
                            request.packageValue = orderInfo.getOrderInfo().getPackageX();
                            request.nonceStr = orderInfo.getNonce_str();
                            request.timeStamp = orderInfo.getOrderInfo().getTimestamp();
                            request.sign = orderInfo.getOrderInfo().getSign();
                            api.sendReq(request);
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取支付信息失败");
                    }
                });
    }


    static class Adapter extends BaseAdapter<CarProductEntity> {

        @NonNull
        @Override
        public BaseViewHolder<CarProductEntity> onCreateViewHolder(@NonNull ViewGroup parent,
                                                                   int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
            View view = layoutInflater.inflate(R.layout.item_order_rlv, parent, false);
            ViewHolder viewHolder = new ViewHolder(view, getDatas());
            return viewHolder;
        }

        @Override
        public int getItemCount() {
            return 1;
        }
    }

    static class ViewHolder extends BaseViewHolder<CarProductEntity> {
        TextView tvTotal;
        TextView tvTotalPrice;
        LinearLayout mLinearLayout;
        List<CarProductEntity> carProductEntities;

        public ViewHolder(@NonNull View itemView, List<CarProductEntity> datas) {
            super(itemView);

            mLinearLayout = itemView.findViewById(R.id.ll);
            tvTotal = itemView.findViewById(R.id.tv_total);
            tvTotalPrice = itemView.findViewById(R.id.tv_total_price);
            int totalPrice = 0;
            carProductEntities = datas;
            for (int i = 0; i < datas.size(); i++) {
                CarProductEntity productEntity = datas.get(i);
                View view = View.inflate(itemView.getContext(), R.layout.item_order_rlv_item, null);
                ImageView ivHead = view.findViewById(R.id.iv_head);
                TextView tvTitle = view.findViewById(R.id.tv_title);
                TextView tvPrice = view.findViewById(R.id.tv_price);
                TextView tvNum = view.findViewById(R.id.tv_num);
                GlideUtil.loadImg(productEntity.getImage(), ivHead);
                tvTitle.setText(productEntity.getTitle());
                tvPrice.setText("￥" + productEntity.getSales_price() + "");
                tvNum.setText("x" + productEntity.getNumber());
                mLinearLayout.addView(view);
                totalPrice += (productEntity.getSales_price() * productEntity.getNumber());
            }
            tvTotal.setText("共" + carProductEntities.size() + "件  小计：");
            tvTotalPrice.setText("￥" + totalPrice);

        }

        @Override
        public void bindViewHolder(CarProductEntity value) {

        }
    }

}